//
//  WeChatManager.m
//  Test
//
//  Created by geng on 2019/8/19.
//  Copyright © 2019 geng. All rights reserved.
//

#import "WeChatManager.h"
#import "WXApi.h"

@implementation WeChatManager
+ (instancetype)sharedManager{
    static WeChatManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[WeChatManager alloc] init];
    });
    return instance;
}
- (void)onResp:(BaseResp *)resp{
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *res = (SendAuthResp *)resp;
        [self loginSuccessByCode:res.code];
    }
}
+ (void)sendAuthRequest{
    SendAuthReq *req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    req.openID = WXAPPID;
    [WXApi sendReq:req];
}
- (void)loginSuccessByCode:(NSString *)code{
    __weak typeof (*&self) weakSelf = self;
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAPPID,WXAPPSECRET,code];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/encryp;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    NSURLSession *sharedSession = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data && (error == nil)) {
            // 网络访问成功
            NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"data=%@",dataStr);
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *accessToken = [dict valueForKey:@"access_token"];
            NSString *openId = [dict valueForKey:@"openid"];
            [weakSelf requestUserInfoByToken:accessToken openId:openId];
            
        } else {
            // 网络访问失败
            NSLog(@"error=%@",error);
        }
    }];
    [dataTask resume];
}
-(void)requestUserInfoByToken:(NSString *)token openId:(NSString *)openId{
    NSString *urlStr = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@&",token,openId];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/encryp;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    NSURLSession *sharedSession = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data && (error == nil)) {
            // 网络访问成功
            NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"data=%@",dataStr);
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"dict%@", dict);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"receiveUserInfo" object:dict];
            //发通知
        } else {
            // 网络访问失败
            NSLog(@"error=%@",error);
        }
    }];
    [dataTask resume];
}

@end
